package com.mc.cloud.mall.common.exception;

import com.mc.cloud.mall.common.common.MallRestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName GlobalExceptionHandler
 * @Author MC
 * @Date 2021/5/20 12:51
 * @Version 1.0
 **/
@ControllerAdvice
public class GlobalExceptionHandler {
    
    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Object handlerException(Exception e){
        log.error("Default Exception" + e);
        return MallRestResponse.error(MallExceptionEnum.SYSTEM_ERROR);
    }
    
    @ResponseBody
    @ExceptionHandler(MallException.class)
    public Object MallHandlerException(MallException e){
        log.error("Mall Exception" + e);
        return MallRestResponse.error(e.getCode(),e.getMessage());
    }
    
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public MallRestResponse handlerMethodArgmentNotValidException(MethodArgumentNotValidException e){
        log.error("MethodArgumentNotValidException" +e);
        return handlerBindingResult(e.getBindingResult());
    }
    
    /**
     * 把异常处理为MallRestResponse
     * @param result
     * @return
     */
    private MallRestResponse handlerBindingResult(BindingResult result){
        //把异常处理为对外暴露的提示
        List<String> list = new ArrayList<>();
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError allError : allErrors) {
                String message = allError.getDefaultMessage();
                list.add(message);
            }
        }
        if (list.size()==0){
            return MallRestResponse.error(MallExceptionEnum.REQUEST_PARAM_ERROR);
        }
        
        return MallRestResponse.error(MallExceptionEnum.REQUEST_PARAM_ERROR.getCode(),list.toString());
    }
}
